import React, { Component } from 'react';
import { Space, Modal, Form, message } from "antd";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import TextArea from "antd/es/input/TextArea";
import { apiGetProviderList,apiGetServicerCashFlow,apiWithdrawCashPass,apiWithdrawCashReject } from '@/request/callReconciliation/accountManage.js';
import moment from 'moment'

//提现申请
export default class WithdrawApply extends Component {
  state = {
    columns: [
      {
        title: "申请编号",
        dataIndex: "servicerCashFlowId",
        key: "servicerCashFlowId",
      },
      {
        title: "服务者id",
        dataIndex: "providerId",
        key: "providerId",
      },
      {
        title: "服务者姓名",
        dataIndex: "providerName",
        key: "providerName",
      },
      {
        title: "类型",
        dataIndex: "businessType",
        key: "businessType",
        render: (text) => {
          return text === 3 && '提现'
        }
      },
      {
        title: "金额(元)",
        dataIndex: "price",
        key: "price",
        render: (text) => {
          return <React.$Price price={text || 0} />
        }
      },
      {
        title: "状态",
        dataIndex: "auditState",
        key: "auditState",
        render: (text) => {
          return text === 0 && '审核中'
        }
      },
      {
        title: "申请时间",
        dataIndex: "applyTime",
        key: "applyTime",
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
        width: 200
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (text, record) => {
          return (
              <div>
                <TheButton haspermi={['call:financialReconcile:withdrawApply:pass']} onClick={() => this.goPass(record)}>通过</TheButton>
                <TheButton haspermi={['call:financialReconcile:withdrawApply:reject']} onClick={() => this.goReject(record)}>驳回</TheButton>
              </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    form_show: true,
    searchOption: [
      {
        field: 'servicerIdList',
        label: '服务者',
        placeholder: '请选择',
        required: false,
        rules: [],
        type: 'Select',
        options: [],
        mode:'multiple',
        otherConfig: {
          filterOption:(input, option) => (option?.children ?? '').includes(input)
        }
      },
      {
        field: 'servicerCashFlowId',
        label: '申请编号',
        placeholder: '请输入',
        required: false,
        rules: [],
        type: 'Input',
        defaultValue: ''
      },
      { field: 'time', label: '申请时间', placeholder: '请选择', required: false, rules: [], type: 'RangePicker' },
    ],
    queryForm: {},
    money: 0,
    passModalVisible: false,
    rejectModalVisible: false,
    servicerCashFlowId: '',//流水主键
    rejectLoading: false, //驳回loading
    passLoading: false, //通过loading
  }

  componentDidMount = async ()=> {
    this.getProviderList()
    this.getData()
  }
  getProviderList = () => {
    apiGetProviderList().then(res=>{
      if (res.code === 0){
        const newArr = res.data.map(item=>{
          return {
            label: item.name + '-' +item.providerId,
            value: item.providerId
          }
        })
        let { searchOption } = this.state;
        searchOption[0].options = newArr;
        this.setState({
          searchOption
        })
      }
    })
  }
  /**
   * @desc 获取资金列表
   * */
  getData = async (value) => {
    const params = {
      ...this.state.pageData,
      ...this.state.queryForm,
      businessType: 3,
      auditStateList: [0]
    }
    apiGetServicerCashFlow({ ...params }).then(res => {
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
        })
      }
    })
  }
  /**
   * @desc 表格组件分页切换
   * @params number|string {pageNo} 页号
   * @params number|string {pageSize} 每页条数
   * */
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };
  /**
   * @desc 表格搜索组件重置搜索条件
   * */
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  /**
   * @desc 表格搜索组件搜索
   * */
  onFormSearch(value) {
    if (value && value.hasOwnProperty('time')) {
      value.beginOrderCreateTime = moment(value.time[0]).format('yyyy-MM-DD') + ' 00:00:00'
      value.endOrderCreateTime = moment(value.time[1]).format('yyyy-MM-DD') + ' 23:59:59'
      delete value.time
    }
    let { queryForm } = this.state;
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: {...value}
    }, () => {
      this.getData()
    })
  }
  /**
   * @desc 开启通过modal
   * */
  goPass = (values) => {
    this.setState({
      money: values.price,
      passModalVisible: true,
      servicerCashFlowId: values.servicerCashFlowId
    })
  }
  passModalOk = async () => {
    this.setState({ passLoading: true })
    // 通过提现申请
    let res = await apiWithdrawCashPass({
      servicerCashFlowId: this.state.servicerCashFlowId
    })
    if (res.code === 0) {
      message.success('申请通过')
      // this.pageChange(1, 10)
    }
    this.pageChange(1, 10)
    this.setState({ passModalVisible: false, passLoading: false })
  }
  /**
   * @desc 开启驳回modal
   * */
  goReject = (values) => {
    this.setState({
      money: values.price,
      rejectModalVisible: true,
      servicerCashFlowId: values.servicerCashFlowId
    })
  }
  rejectModalOk = () => {
    this.setState({ rejectLoading: true })
    // 驳回提现申请
    this.formRef.validateFields().then(async (values) => {
      let res = await apiWithdrawCashReject({
        ...values,
        servicerCashFlowId: this.state.servicerCashFlowId
      })
      if (res.code === 0) {
        message.success('驳回成功')
      }
      this.pageChange(1, 10)
      this.setState({ rejectModalVisible: false })
    })
    this.setState({ rejectLoading: false })
  }
  render() {
    let {
      money,
      passModalVisible,
      rejectModalVisible,
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      searchOption,
      form_show,
      rejectLoading,
      passLoading
    } = this.state;
    return (
        <div className={"p-layout-box commodity-content"}>
          <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                        onGetValues={(values) => this.onFormSearch(values)}
                        onReset={(values) => this.onReset(values)}
          >
          </TheQueryForm>
          <TheTable
              scroll={{ x: '960', y: '63vh' }}
              columns={columns}
              dataSource={dataSource}
              rowKey={'storeCashFlowCommissionId'}
          />
          <ThePagination
              pageNo={pageNo}
              pageSize={pageSize}
              total={total}
              pageChange={this.pageChange}
          />
          <Modal
              title="提醒"
              visible={passModalVisible}
              okText={"通过"}
              onOk={this.passModalOk}
              confirmLoading={passLoading}
              onCancel={() => this.setState({ passModalVisible: false })}
          >
            审核通过后，该笔款项（<React.$Price price={money || 0} />）将直接转账至服务者账户中，是否继续通过?
          </Modal>
          <Modal
              title="提醒"
              visible={rejectModalVisible}
              okText={"驳回"}
              destroyOnClose={true}
              onOk={this.rejectModalOk}
              confirmLoading={rejectLoading}
              onCancel={() => this.setState({ rejectModalVisible: false })}

          >
            <p>驳回后，该服务者将无法提现该笔款项（<React.$Price price={money || 0} />）至账户中，是否继续？</p>
            <Form
                labelCol={{
                  span: 4,
                }}
                wrapperCol={{
                  span: 19,
                }}
                layout="horizontal"
                ref={(ref) => this.formRef = ref}
            >
              <Form.Item label="驳回原因" name={"rejectReason"} rules={[{ required: true }]}>
                <TextArea rows={4} maxLength={200} showCount allowClear />
              </Form.Item>
            </Form>
          </Modal>
        </div>
    );
  }
}
